package util;

import common.Constants;
import redis.clients.jedis.Tuple;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 文件输出类 简化一点操作
 * <p>
 * 使用时
 *
 * @see FileUtil(String) 不用担心父文件夹不存在 会直接mkdirs
 * 写文件时 使用
 * @see #writeln(String, String...)
 * 写完之后需要用
 * @see #flush()
 * @see #close()
 * <p>
 * <p>
 * Created by J.Chen on 2017/5/27.
 */
public class FileUtil {
    private String filePath;
    private File file;
    private FileWriter fileWriter;

    /**
     * @param filePath
     * @return
     * @throws IOException
     */
    public static List<String> readFile(String filePath) throws IOException {
        List<String> list = new ArrayList<>();
        BufferedReader fin = new BufferedReader(new FileReader(new File(filePath)));

        return fin.lines().collect(Collectors.toList());
    }

    public FileUtil(String remoteName, String... values) {
        this(String.format(Constants.outputDir + String.join(".", values) + "." + remoteName + ".txt"));
    }

    public FileUtil(String filePath) {
        this.filePath = filePath;
        file = new File(this.filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            fileWriter = new FileWriter(file);
        } catch (IOException e) {
        }
    }

    public void writeTuple(Set<Tuple> set) {
        for (Tuple t : set) {
            writeln("|", t.getElement(), "" + t.getScore());
        }
    }

    public void writeMysqlList(List<Map<String, String>> list, String split, String... keys) {
        writeln("|", keys);
        for (Map<String, String> map : list) {
            List<String> values = new ArrayList<>();
            for (String key : keys) {
                values.add(map.get(key));
            }
            writeln(split, values.toArray(new String[values.size()]));
        }
    }


    public void writeln(String split, String... values) {
        try {
            for (int i = 0; i < values.length; i++) {
                fileWriter.append(String.valueOf(values[i]));
                if (i < values.length - 1) {
                    fileWriter.append(split);
                }
            }
            fileWriter.append("\n");
        } catch (IOException e) {
        }
    }

    public void close() {
        try {
            flush();
            fileWriter.close();
        } catch (IOException e) {
        }
    }

    public void flush() {
        try {
            fileWriter.append("\n");
            fileWriter.flush();
        } catch (IOException e) {
        }
    }
}